<template>
  <div>
    <!-- 新增修改表单 -->
    <el-dialog
      width="50%"
      :title="textMap[dialogStatus]"
      :visible.sync="DialogFormVisibleCom"
      append-to-body
    >
      <div class="myfrom1002">
        <el-form ref="dataForm" :rules="rules" :model="formSubmitDataCom" label-position="right" label-width="110px"
                 style="width: 90%; margin:10px auto;">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="节点名称">
                <el-input
                  v-model="sonCurrentRow.coa_name"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="节点编号">
                <el-input
                  v-model="sonCurrentRow.coa_code"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>

            <!-- 定价方法 -->
            <el-col :span="12">
              <el-form-item label="定价方法" prop="cust_action">
                <el-select
                  v-model="formSubmitDataCom.cust_action"
                  class="filter-item"
                  placeholder="Please select"
                  :disabled="false"
                >
                  <el-option v-for="item in pricingOptions" :key="item.code" :label="item.name" :value="item.code"/>
                </el-select>
              </el-form-item>
            </el-col>


            <component
              :is="sonTempName"
              :formSubmitData="formSubmitData"
              :pricingChangesOptons="pricingChangesOptons"
              @findFindcurvetermEmit="findFindcurvetermEmit"
            ></component>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button @click="resetFormData">
          重置
        </el-button>
        <el-button type="primary" @click="dialogStatus==='udateSave'?updateSaveData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import XEUtils from 'xe-utils'
import {filterAllRowBynormData} from '@/utils/index'
import PricingSubmitFormAItem from "./PricingSubmitFormAItem"
import PricingSubmitFormBItem from "./PricingSubmitFormBItem"
import PricingSubmitFormCItem from "./PricingSubmitFormCItem"
import PricingSubmitFormDItem from "./PricingSubmitFormDItem"

export default {
  name: 'PricingSubmitForm',
  components: {
    PricingSubmitFormAItem,
    PricingSubmitFormBItem,
    PricingSubmitFormCItem,
    PricingSubmitFormDItem
  },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false
    },
    dialogStatus: {
      type: String,
    },
    formSubmitData: {
      type: Object,
      default: function () {
        return {}
      }
    },
    watchPricingFormSubmitData: {
      type: Object,
      default: function () {
        return {}
      }
    },
    /* 定价方法options */
    pricingOptions: {
      type: Array
    },
    /* 当前选中方案 */
    currentRow: {
      type: Object,
      default() {
        return {}
      }
    },
    /* 当前选中节点 */
    sonCurrentRow: {
      type: Object,
      default() {
        return {}
      }
    },
    /* 定价方法可变表单项相关的options */
    pricingChangesOptons: {
      type: Object,
      default() {
        return {}
      }
    },
    isCustAction: {
      type: Boolean,
      default: false
    },
  },
  // 定义属性
  data() {
    // /* 生效日期验证 */
    // var validateDateRangeSdate = (rule, value, callback) => {
    //   if (XEUtils.isEmpty(value)) {
    //     callback(new Error('生效日期必填!'));
    //   } else if ((!XEUtils.isEmpty(this.formSubmitDataCom.e_date)) && (value > this.formSubmitDataCom.e_date)) {
    //     callback(new Error('生效日期必须小于失效日期!'));
    //   } else {
    //     callback();
    //   }
    // };
    // /* 失效日期验证 */
    // var validateDateRangeEdate = (rule, value, callback) => {
    //   if (XEUtils.isEmpty(value)) {
    //     callback(new Error('失效日期必填!'));
    //   } else if ((!XEUtils.isEmpty(this.formSubmitDataCom.s_date)) && (value < this.formSubmitDataCom.s_date)) {
    //     callback(new Error('失效日期必须大于生效日期!'));
    //   } else {
    //     callback();
    //   }
    // };

    return {
      textMap: {
        update: '修改',
        create: '新增',
        udateSave: '定价方法-更新&保存'
      },
      sonTemp: {
        aTemp: ['1', '2', '3', '4'],
        bTemp: ['5', '6'],
        cTemp: ['7', '8'],
        dTemp: ['9']
      },
      sonTempName: '',
      rules: {
        // tp_id: [{required: true, message: '期限方案必填', trigger: 'change'}],
        // s_date: [{validator: validateDateRangeSdate, trigger: 'change'}],
        // e_date: [{validator: validateDateRangeEdate, trigger: 'change'}],
        // type: [{ required: true, message: 'type is required', trigger: 'change' }],
        // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        // title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      // 表单用到的值
      // calendarTypeOptions,
      // statusOptions: ['published', 'draft', 'deleted'],
    }
  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {
    DialogFormVisibleCom: {
      get() {
        return this.dialogFormVisible
      },
      set(val) {
        this.$emit('update:dialogFormVisible', val)
      }
    },
    isCustActionCom: {
      get() {
        return this.isCustAction
      },
      set(val) {
        this.$emit('update:isCustAction', val)
      }
    },
    formSubmitDataCom: {
      get() {
        return this.formSubmitData
      },
      set(val) {
        this.$emit('update:formSubmitData', val)
      }
    },
    formSubmitData_cust_action() {
      return this.formSubmitData.cust_action
      // return {
      //   cust_action:this.formSubmitData.cust_action,
      //   // id: this.formSubmitData.id,
      // }
    }
  },
  // 监控data中的数据变化
  watch: {
    watchPricingFormSubmitData:{
      handler(nObj, o) {
        console.log('person changed');
        this.resetFormSubmitDataAndStyle(nObj.cust_action, o)
      },
      deep: true,
      // immediate: true
    },
    formSubmitData_cust_action(n, o){
        this.resetFormSubmitDataAndStyle(n, o)
    }
  },
  // 方法集合
  methods: {
    findFindcurvetermEmit(nObj){
      this.$emit('findFindcurvetermEmit2', nObj)
    },

    /* 重置表单样式和值 */
    resetFormSubmitDataAndStyle(n, o) {

      // const n = nObj.cust_action
      console.log('nnnnnnnnnnnnnnnnnnnnnnnnnnnnn', n);
      if (!XEUtils.isEmpty(n)) {


        console.log('this.formSubmitDataComthis.formSubmitDataCom11',this.formSubmitDataCom);
        // 初始化formSubmitDataCom
        console.log('珊瑚是胜多负少的fasflksajfldj', this.isCustActionCom);
        if (!this.isCustActionCom) {

          this.formSubmitDataCom = filterAllRowBynormData({
            allRow: this.formSubmitData,
            normData: {
              id:'',
              cust_action: '',
            }
          })
        }

        console.log("8888888888888888888888888888888888888");

        console.log('this.formSubmitDataComthis.formSubmitDataCom22',this.formSubmitDataCom);

        // this.$set(this.formSubmitDataCom, "adj_type", '')


        
        // 将回调延迟到下次 DOM 更新循环之后执行
        this.$nextTick(() => {
          if (XEUtils.includes(this.sonTemp.aTemp, n)) {
            

            // cv_gp_code(转移曲线组编号（下拉框）) ，adj_type（取点方法（下拉框）），bl_cur_rate（执行利率保底）
            if (!this.isCustAction) {
              this.$set(this.formSubmitDataCom, "cv_gp_code", '')
              this.$set(this.formSubmitDataCom, "adj_type", '')
              this.$set(this.formSubmitDataCom, "bl_cur_rate", '')
            }

            this.sonTempName = 'PricingSubmitFormAItem'
          }

          // console.log('this.formSubmitDataComthis.formSubmitDataCom',this.formSubmitDataCom);

          if (XEUtils.includes(this.sonTemp.bTemp, n)) {
            // 56：cv_gp_code(转移曲线组编号（下拉框）) ，
            // term_code （期限编码（下拉框）），
            //  adj_value （调整点差值），
            // adj_type（调整单位（下拉框））
            if (!this.isCustAction) {
              this.$set(this.formSubmitDataCom, "cv_gp_code", '')
              this.$set(this.formSubmitDataCom, "term_code", '')
              this.$set(this.formSubmitDataCom, "adj_value", '')
              this.$set(this.formSubmitDataCom, "adj_type", '')
            }

            this.sonTempName = 'PricingSubmitFormBItem'
          }
          if (XEUtils.includes(this.sonTemp.cTemp, n)) {
            // 78：cv_gp_code(转移曲线组编号（下拉框）) ，adj_type（取点方法（下拉框））
            // ，bl_value（保底值），bl_type（保底单位（下拉框））
            if (!this.isCustAction) {
              this.$set(this.formSubmitDataCom, "cv_gp_code", '')
              this.$set(this.formSubmitDataCom, "adj_type", '')
              this.$set(this.formSubmitDataCom, "bl_value", '')
              this.$set(this.formSubmitDataCom, "bl_type", '')
            }

            this.sonTempName = 'PricingSubmitFormCItem'
          }
          if (XEUtils.includes(this.sonTemp.dTemp, n)) {
            // 9：lk_value（锁定价差值），lk_type（锁定类型（下拉框））
            if (!this.isCustAction) {
              this.$set(this.formSubmitDataCom, "lk_value", '')
              this.$set(this.formSubmitDataCom, "lk_type", '')
            }
            this.sonTempName = 'PricingSubmitFormDItem'
          }
          this.isCustActionCom = false
        })

      }else{
        this.sonTempName = ''
      }
    },

    resetFormData() {
      console.log("IIIIIIIIIIUUUUUUUUUUUUUUUUU");
      let exclude = []
      if (this.dialogStatus === 'create') {
        exclude = [
          'cv_name',
          'curr_name',
          'e_date'
        ]
      }
      console.log('this.dialogStatusthis.dialogStatus', this.dialogStatus);
      if (this.dialogStatus === 'update') {
        exclude = [
          'cv_name',
          'curr_name',
          'tp_id'
        ]
      }
      console.log('exclude', exclude);

      this.$emit('resetFormDataEmit', {
        exclude
      })

    },

    updateSaveData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$emit('handleFromUpdateSaveDataEmit')
        }
      })
    },

    // updateData() {
    //   this.$refs['dataForm'].validate((valid) => {
    //     if (valid) {
    //       const tempData = Object.assign({}, this.formSubmitData)
    //       this.$emit('handlePricingFromUpdateDataEmit')
    //       // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
    //       // updateArticle(tempData).then(() => {
    //       //   const index = this.list.findIndex(v => v.id === this.temp.id)
    //       //   this.list.splice(index, 1, this.temp)
    //       //   this.dialogFormVisible = false
    //       //   this.$notify({
    //       //     title: 'Success',
    //       //     message: 'Update Successfully',
    //       //     type: 'success',
    //       //     duration: 2000
    //       //   })
    //       // })
    //     }
    //   })
    // },

  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    console.log('formSubmitDataformSubmitData222', this.formSubmitData);
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  beforeCreate() {
  }, // 生命周期 - 创建之前
  beforeMount() {
  }, // 生命周期 - 挂载之前
  beforeUpdate() {
  }, // 生命周期 - 更新之前
  updated() {
  }, // 生命周期 - 更新之后
  beforeDestroy() {
  }, // 生命周期 - 销毁之前
  destroyed() {
  }, // 生命周期 - 销毁完成
  activated() {
  }, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='scss' scoped>
.myfrom1002 {
  ::v-deep {
    .el-col-12 {
      height: 58px;
    }

  }
}


</style>